package controller.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 图片展示工具类控制器
 */
@Controller
public class ImgDisplayUtilsController {

    private final Logger logger = LoggerFactory.getLogger(ImgDisplayUtilsController.class);

    @Value("${yd.img.path}")
    private String commonImgPath;

    @GetMapping("/utils/imgDisplay")
    public void doDisplay(HttpServletRequest request, HttpServletResponse response){
        Pattern pattern = Pattern.compile("^[a-zA-Z0-9]{32}[.][a-zA-Z]{3,4}$");

        String imgPath = request.getParameter("img");
        try {
            // 传入参数为空处理
            if(imgPath == null){
                response.sendError(404);
                return;
            }

            // 文件名是否合法
            Matcher matcher = pattern.matcher(imgPath);
            if(!matcher.matches()){
                response.sendError(404);
                return;
            }

            String avatarPath = commonImgPath + imgPath;
            File file = new File(avatarPath);

            // 判断：文件是否存在 || 文件是否可读 || 文件是一个文件还是一个文件夹
            if( file.exists() && file.canRead() && file.isFile() ){
                // 获取文件类型
                String fileName = file.getName();
                String fileType = "image/" + fileName.substring(fileName.lastIndexOf(".")+1);

                // 读取文件
                FileInputStream inputStream = new FileInputStream(file);
                byte[] fileData = new byte[inputStream.available()];
                int fileLength = inputStream.read(fileData);
                inputStream.close();

                // 返回
                response.setContentType(fileType);
                response.setContentLength(fileLength);
                OutputStream out = response.getOutputStream();
                out.write(fileData);
                out.flush();
                out.close();
            }else{
                response.sendError(404);
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("获取用户头像失败，文件名："+imgPath);
        }
    }
}
